package web

import (
	"github.com/gin-gonic/gin"
	uuid "github.com/lithammer/shortuuid/v4"
	"net/http"
	"webook/internal/service"
)

type Oauth2WechatHandler struct {
	svc     service.WeChatService
	userSvc service.IUserService
	JwtHandler
}

func NewOauth2WechatHandler(svc service.WeChatService, userSvc service.IUserService) *Oauth2WechatHandler {
	return &Oauth2WechatHandler{
		svc:     svc,
		userSvc: userSvc,
	}
}

func (h *Oauth2WechatHandler) AuthURL(ctx *gin.Context) {
	state := uuid.New()
	url, err := h.svc.AuthURL(ctx, state)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 5,
			"msg":  "系统错误",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": url,
	})
}

func (h *Oauth2WechatHandler) VerifyCode(ctx *gin.Context) {
	// 1. 获取code
	code := ctx.Query("code")
	// 2. 获取state
	state := ctx.Query("state")
	// 3. 校验临时授权码
	info, err := h.svc.VerifyCode(ctx, code, state)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 5,
			"msg":  "系统错误",
		})
		return
	}
	// 4. 登录设置jwt token
	user, err := h.userSvc.FindOrCreateByWeChat(ctx, info)
	if err == service.ErrUserDuplicate {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 4,
			"msg":  "用户已存在!",
		})
		return
	}
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 5,
			"msg":  "系统错误!",
		})
		return
	}
	err = h.SetLoginToken(ctx, user.Id)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 5,
			"msg":  "系统错误!",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户登录成功!",
	})

}

func (h *Oauth2WechatHandler) RegisterRoutes(server *gin.Engine) {
	g := server.Group("/oauth2/wechat")
	g.GET("/authurl", h.AuthURL)
	g.Any("/callback", h.VerifyCode)
}
